import CryptoJS from 'crypto-js'

const KEY = CryptoJS.enc.Utf8.parse("xxx")
const IV = CryptoJS.enc.Utf8.parse('xxx')
const options = {
    iv: IV,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
}

/**
 * 加密
 * @param word
 * @returns {string}
 * @constructor
 */
export const Encrypt = (word) => {
    let srcs = CryptoJS.enc.Utf8.parse(word)
    const encrypted = CryptoJS.AES.encrypt(srcs, KEY, options)
    return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}

/**
 * 解密方法
 * @param word
 * @returns {string}
 * @constructor
 */
export const Decrypt = (word) => {
    let base64 = CryptoJS.enc.Base64.parse(word);
    let src = CryptoJS.enc.Base64.stringify(base64);
    let decrypt = CryptoJS.AES.decrypt(src, KEY, options);
    return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}

/**
 *
 * @param a
 * @param idStr
 * @param pidStr
 * @param childrenStr
 * @returns {*[]}
 */
export const transformToTreeFormat = (
    a, //
    idStr,
    pidStr,
    childrenStr = "children"
) => {
    let [r, hash, id, pid, children, i, j, len] = [
        [],
        {},
        idStr,
        pidStr,
        childrenStr,
        0,
        0,
        a.length
    ];
    for (; i < len; i++) {
        hash[a[i][id]] = a[i];
    }
    for (; j < len; j++) {
        let aVal = a[j];
        let hashVP = hash[aVal[pid]];
        if (hashVP) {
            !hashVP[children] && (hashVP[children] = []);
            hashVP[children].push(aVal);
        } else {
            r.push(aVal);
        }
    }
    return r;
};

export const Json2Xml = function(tag, props = {}, level = 0) {
    this.tag = tag;
    this.cols = [];
    this.level = level;
    this.setLevel = (level) => {
        this.level = level
        this.cols.forEach(e => e.setLevel(level + 1))
    };
    this.append = (child) => {
        child.setLevel(level + 1)
        this.cols.push(child)
    };
    this._attrs = (props) => {
        if (props == null) {
            return ''
        }
        return ['', ...Object.keys(props).map((e) => [e, props[e]]).reduce((cols, e) => {
            return cols.push([e[0], ['"', e[1] || '', '"'].join('')].join("=")), cols
        }, [])].join(' ')
    };
    this.prefix = () => {
        return ['\n', ...(Array.from(new Array(this.level), () => '\t'))]
    };
    this.toString = () => {
        return [
            ...(this.level > 0 ? this.prefix() : ['']),
            ...['<', tag, this._attrs(props),  '>'],
            ...this.cols,
            ...(this.cols.length > 0 ? this.prefix() : ['']),
            '</' + tag + '>'
        ].join('')
    };
}
